import wepy from 'wepy'
import api from '@/api/api'
import {imgurl,WXREGISTER,SUBMITDATA,SYMPTOM_FILLING,VISITING_EXPERIENCE} from '@/utils/constant';
import {removeDuplicatedItem_msg} from '@/utils/utils';
export default class dialogue extends wepy.mixin {
  data = {
    result:null,
    formIdString:null,
    msg_text:"",
    isOrderSn:null, 
    btnIsShow:false,
    msgList:[],
    timer:null,
    evaluateIsShow:false,
    oneself_msg:null,
    OtherParty_msg:null
  }

  methods = {
    //获取输入框消息
    getContent(e)
    {
      this.msg_text = e.detail.value;
      this.btnIsShow = !this.btnIsShow;
      this.$apply();
    },
    //用户端发送消息
    async sendMessage(e)
    {
      await this.requestSendMsg({
        fromId:wepy.getStorageSync(WXREGISTER).id,
        toId:this.result.expertExtInfo.member_id,
        msgText:this.msg_text,
        msgType:0,
        formId:e.detail.formId,
        order_sn:this.isOrderSn
      })
      this.msg_text = "";
      this.$apply();
    },

  //专家端发送消息
  async sendMessage_expert(e)
  {
    await this.requestSendMsg({
      fromId:wepy.getStorageSync(WXREGISTER).id,
      toId:this.result.member.id,
      msgText:this.msg_text,
      msgType:0,
      formId:e.detail.formId,
      order_sn:this.isOrderSn
    })
    this.msg_text = "";
    this.$apply();
  },
  //用户端发送图片
  choicePic(e)
  {
    wepy.chooseImage({
      count: '1', //最多可以选择的图片张数,
      success: res => {
        wepy.showToast({
          title: '正在发送', 
          icon: 'loading',  
          mask: true,  
          duration: 10000 
        }); 
        this.uploadFile({name:'pic',filepath:res.tempFilePaths[0]}).then((res) => {
          if(res.status == "success")
          {
            this.requestSendMsg({
              fromId:wepy.getStorageSync(WXREGISTER).id,
              toId:this.result.expertExtInfo.member_id,
              msgImg:res.data.filePath,
              msgType:2,
              formId:e.detail.formId,
              order_sn:this.isOrderSn
            })
          }
        })
       wepy.hideToast(); 
        this.$apply();
      }
    });
  },
  //专家端发送图片
  choicePic_expert(e)
  {
    wepy.chooseImage({
      count: '1', //最多可以选择的图片张数,
      success: res => {
        wepy.showToast({
          title: '正在发送', 
          icon: 'loading',  
          mask: true,  
          duration: 10000 
        }); 
        this.uploadFile({name:'pic',filepath:res.tempFilePaths[0]}).then((res) => {
          if(res.status == "success")
          {
            this.requestSendMsg({
              fromId:wepy.getStorageSync(WXREGISTER).id,
              toId:this.result.member.id,
              msgImg:res.data.filePath,
              msgType:2,
              formId:e.detail.formId,
              order_sn:this.isOrderSn
            })
          }
        })
       wepy.hideToast(); 
        this.$apply();
      }
    });
  },
    //点击图片预览
    clickPreviewImage(e)
    {
      this.previewImage([e.currentTarget.dataset.url])
    },

    //结束咨询
    endConsultation()
    {
      this.isOrderSn
      wepy.showModal({
        title: '咨询提示', 
        content: '是否结束咨询', 
        showCancel: true, //是否显示取消按钮,
        cancelText: '取消', //取消按钮的文字，默认为取消，最多 4 个字符,
        cancelColor: '#000000', //取消按钮的文字颜色,
        confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
        confirmColor: '#3CC51F', //确定按钮的文字颜色,
        success: res => {
          if(res.confirm)
          {
            api.EndConsult({
              query:{
                order_sn:this.isOrderSn
              },
              method:"GET"
            }).then((res) => {
              if(res.status == "success")
              {
                this.clearTimer();
                wepy.showToast({
                  title: '本次咨询结束', //提示的内容,
                  icon: 'success', //图标,
                  duration: 3000, //延迟时间,
                  mask: true, //显示透明蒙层，防止触摸穿透,
                  success: res => {
                    if(res.errMsg == "showToast:ok")
                    {
                      wepy.reLaunch({ url: 'xi' });
                    }
                  }
                });
              }
              else
              {
                wepy.showToast({
                  title:res.msg, //提示的内容,
                  icon: 'none', //图标,
                  duration: 2000, //延迟时间,
                  mask: true, //显示透明蒙层，防止触摸穿透,
                  success: res => {
                    setTimeout(() => {
                      wepy.reLaunch({ url: 'xi' });
                    },1000)
                  }
                });
              }
            }).catch((err) => {
                wepy.showToast({
                  title: res.msg, 
                  icon: 'none'
                });
            })
          }
        }
      });
    },
  }

  onShow() {
  }
  onUnload() {
    this.clearTimer()
};
  async onLoad(e) {
   // this.usertype = e.reqtype;
    // if(e.id)
    // {
    //   if(e.id == 0) 
    //   {
    //     this.isOrderSn = await wepy.getStorageSync(SUBMITDATA).ext_order_sn;
    //   }
    //   else if(e.id == 1)
    //   {
    //     this.isOrderSn = await e.ordersn;
    //   }
    // }

//     await this.dataInit(e.reqtype).then((res) => {
//       if(res.status == "success")
//       {
//           if(e.reqtype == "user" && typeof res.data.expertExtInfo.member_images == 'string' && typeof res.data.expertExtInfo.member_qrcode == 'string')
//           {
//             res.data.expertExtInfo.member_images = JSON.parse(res.data.expertExtInfo.member_images)
//             res.data.expertExtInfo.member_qrcode = JSON.parse(res.data.expertExtInfo.member_qrcode)
//           }
//           this.result = res.data;
//           //对话消息处理
//           let identity; //true:自己，false:对方
//           let messagelist = res.data.messagelist;
//           for(let i = 0; i < messagelist.length; i++)
//           {
//             if(messagelist[i].fromId == wepy.getStorageSync(WXREGISTER).id)
//             {
//               identity = true
//             }
//             else
//             {
//               identity = false;
//             }
//               this.msgList.unshift({
//                 identity:identity,
//                 msgdata:messagelist[i].msgText || messagelist[i].msgImg || messagelist[i].video || messagelist[i].audio,
//                 msgtype:messagelist[i].msgType,
//                 msg_time:messagelist[i].msg_time
//               }
//             )
//           }
//           this.$apply();
//       }
//       else
//       {
//           wepy.showModal({
//             title: '提示', //提示的标题,
//             content: res.msg, //提示的内容,
//             showCancel: false, //是否显示取消按钮,
//             confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
//             confirmColor: '#3CC51F', //确定按钮的文字颜色,
//             success: res => {
//               if(res.confirm)
//               {
//                 wepy.switchTab({ url: 'xi' });
//               }
//             }
//           });
//       }
//     }).catch((err) => {
//       wepy.showModal({
//         title: '提示', //提示的标题,
//         content: '数据初始化失败，请重试！', //提示的内容,
//         showCancel: false, //是否显示取消按钮,
//         confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
//         confirmColor: '#3CC51F', //确定按钮的文字颜色,
//         success: res => {
//           if(res.confirm)
//           {
//             wepy.switchTab({ url: 'xi' });
//           }
//         }
//       });
      
//       wepy.showToast({
//         title: '', 
//         icon: 'none'
//       }); 
//     })

//  await this.GetNewMsg();
  }

    //数据初始化----用户/专家
    // async dataInit(reqtype)
    // {
    //     let request;
    //     let reqType = !reqtype ? "expert" : reqtype;
    //     if(reqType == 'user')
    //     {
    //       //如果请求类型为用户
    //       request = await api.ConsultReply({
    //         query:{
    //           order_sn:this.isOrderSn
    //         },
    //         method:"GET"
    //       })
    //     }
    //     else
    //     {
    //       //如果请求类型为专家
    //       request = await api.ExpertConsultReply({
    //         query:{
    //           order_sn:this.isOrderSn
    //         },
    //         method:"GET"
    //       })
    //     }

    //     return request;
    // }
    
  //清除定时
  async clearTimer()
  {
    await clearInterval(this.timer)
    this.timer = null;
    this.$apply();
  }
  //定时查询新消息
  async GetNewMsg()
  {
      let nowTime = new Date();
      this.timer = await setInterval(() => {
        if(new Date() - nowTime > 500)
        {
          api.GetNewMsg({
            query:{
              MyId:wepy.getStorageSync(WXREGISTER).id,
              order_sn:this.isOrderSn
            }
          }).then((res) => {
            if(res.status == "success")
            {
              let messagelist = res.data;
              for(let i = 0; i < messagelist.length; i++)
              {
                this.msgList.push({
                  identity:false,
                  msgdata:messagelist[i].msg_text || messagelist[i].msg_image || messagelist[i].msg_video || messagelist[i].msg_audio,
                  msgtype:messagelist[i].msg_type,
                  msg_time:messagelist[i].msg_time
                })
              }
              this.$apply();
            }
            else
            {
              this.evaluateIsShow = !this.evaluateIsShow;
              this.clearTimer();
            }
          }).catch((err) => {
            wepy.showModal({
              title: '提示', //提示的标题,
              content: '查询新消息失败，请重试！', //提示的内容,
              showCancel: false, //是否显示取消按钮,
              confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
              confirmColor: '#3CC51F', //确定按钮的文字颜色,
              success: res => {
                if(res.confirm)
                {
                  wepy.switchTab({ url: 'xi' });
                }
              }
            });
          })
          this.pageScroll();
        }
      },10000)
  }

  //上传图片
  async uploadFile(obj)
  {
    let result;
    await api.uploadFile({
      filepath:obj.filepath,
      name:obj.name || "",
      memberid:wepy.getStorageSync(WXREGISTER).id
    }).then((res) => {
        if(typeof res.data == 'string')
        {
          result = JSON.parse(res.data);
        }
        if(result.status == "success")
        {
          wepy.showToast({
            title: '文件上传成功！', 
            icon: 'none'
          });
        }
        else
        {
          wepy.showToast({
            title:result.msg, 
            icon: 'none'
          });
        }
    }).catch((err) => {
      wepy.showToast({
        title: '文件上传失败，请重新上传！', 
        icon: 'none'
      });
    });

    return result;
  };



  //发送消息
  async requestSendMsg(obj)
  {
    let queryData = {};
    queryData.fromId = obj.fromId;
    queryData.toId = obj.toId;
    queryData.msgText = obj.msgText || "";
    queryData.video = obj.video || "";
    queryData.audio = obj.audio || "";
    queryData.msgImg = obj.msgImg || "";
    queryData.msgType = obj.msgType;
    queryData.msg_duration = obj.msg_duration || 0;
    queryData.formId = obj.formId;
    queryData.order_sn = obj.order_sn;
    await api.SendMsg({
      query:queryData
    }).then((res) => {
      if(res.status == "success")
      {
        this.msgList.push({
          identity:true,
          msgdata:queryData.msgText || queryData.msgImg || queryData.video || queryData.audio,
          msgtype:obj.msgType
        })
        this.$apply();
      }
      else
      {
        wepy.showToast({
          title: res.msg, 
          icon: 'none'
        });
      }
    }).catch((err) => {
      wepy.showToast({
        title: '消息发送失败，请重试！', 
        icon: 'none'
      });
    })
    await this.pageScroll();
  }

  //预览图片
  previewImage(url)
  {
    wepy.previewImage({
      current:url[0],
      urls: url//需要预览的图片链接列表,
    });
  }

  //让新消息显示在最底部
  async pageScroll() {
    let num_windowHeight;
    let num_elementHeight;
    let that = this;
    await wepy.getSystemInfo({ success: res => {
        num_windowHeight = res.windowHeight;
    } });

    const query = await wx.createSelectorQuery()
    query.select('#consultation-pages').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function(res){
        num_elementHeight = res[0].height
        if(num_elementHeight > num_windowHeight)
        {
            wepy.pageScrollTo({
            scrollTop: num_elementHeight, //滚动到页面的目标位置（单位px）,
            duration: 500, //滚动动画的时长，默认300ms，单位 ms,
            success:function (res) {
            }
            });
        }
    })
}
}
